package com.lmpop.updateHtml.parseHtml;

import com.lmpop.frame.dao.JdbcDbm;
import com.lmpop.updateHtml.parseXml.Config;
import com.lmpop.updateHtml.parseXml.ParseHtml;
import com.lmpop.updateHtml.updateHtml.SpecialField;
import com.lmpop.updateHtml.util.FileUtil;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UpdateHtml
{
  private FileUtil fileUtil = new FileUtil();
  private TagUtil tagUtil;
  private ParseNoonloop parseNoonLoop = new ParseNoonloop();
  private ParseLoop parseLoop = new ParseLoop();
  private String cmsName;
  public ParseHtml parseHtml;
  public InfoVo infoVo;
  public Config conf;
  public String ecms_path;
  public boolean articlelistTagEnable = false;
  private SpecialField sField;
  private static Config cfg;
  private static String noimg_path;
  private static String webtitle;
  private static String weburl;
  private static String icp_filepath;
  private static String icpno;
  private static String reg_send_mail;
  private static String is_reg;
  private static String lose_reason;
  private static String logourl;
  private static String goodss_list_url;
  private static String goods_article_path;
  private static String company_shop_path;

  public UpdateHtml()
  {
    this.parseHtml = new ParseHtml();
    this.conf = new Config();
    this.conf.init();
    this.cmsName = this.conf.getString("cms_name");

    this.infoVo = new InfoVo();
    this.ecms_path = this.conf.getString("rootpath");
    this.tagUtil = new TagUtil();
    this.sField = new SpecialField();
  }

  public void updateArticle(String model, String article_temp, String save_dir, Hashtable paramMap)
  {
    try {
      String temp_file = this.ecms_path + article_temp;
///templets/html/shop/goods_detail.html
      String inStr = this.fileUtil.getContentFromFile(temp_file);
      JdbcDbm jdbcDbm = new JdbcDbm();
      inStr = updateHtml(inStr, paramMap);

      Config configA = new Config("article.properties");
      //model :goods 
      // sql:  select g.goods_id info_id,
      		//(select file_path from ti_attach where 
      			//attach_root_id = g.goods_id and validity='0' and file_type='3' limit 1 ) as small_path,
      		//(select file_path from ti_attach where 
      			//attach_root_id = g.goods_id and validity='0' and file_type='2' limit 1 ) as big_path,
      		//(select ROUND(avg(info_level),2) avg_level from ti_custcomment where  
      			//goods_id=g.goods_id and  1=1 group by goods_id) as avg_level ,
      		//(select count(*)  from ti_custcomment where  
      			//goods_id=g.goods_id and  1=1 group by goods_id) as com_num ,
      		//round((sale_price/market_price)*10,1) as goods_discount,
      		//round(market_price-sale_price,1) as price,
      		//dis.offer_type,dis.discount_id,dis.member_level,dis.spending,dis.number,dis.discount,
      		//t.gift_name,dis.ship_offer dis_shipoffer,g.goods_no,g.cust_id,
      		//(select cust_name from ti_member where cust_id=g.cust_id) as cust_name,
      		//g.class_attr,g.brand_id,g.goods_name title,g.member_price,g.org_price,g.market_price,g.sale_price,g.send_inter,g.buy_inter,g.weight,g.stock_in,g.stock_num,g.stock_out,g.stock_down,
      		//ship_fare,g.goods_desc,g.link_goods,g.link_fit,g.attr_desc,g.publish_date in_date,d.title brand_name 
      		//from ti_goods g 
      		//left join ti_discountpolicy dis //on g.discount_id=dis.discount_id 
      		//left join ti_gift t //on dis.gift_ids=t.gift_id 
      		//left join ti_brand d //on g.brand_id=d.info_id 
      		//where <info_id> g.goods_id='<info_id-value/>' AND </info_id> 1=1  order by g.publish_date desc
      String dySql = configA.getString(model);
      if (dySql.equals(""))
        return;
      String sql = this.tagUtil.getReplaceSqlByMap(dySql, paramMap);
      List infoList = null;
      if ((paramMap != null) && (paramMap.get("row") != null) && (!paramMap.get("row").toString().equals("0")))
      {
        infoList = this.infoVo.getInfoList(sql, paramMap);
      }
      else
      {
        infoList = this.infoVo.getInfoListArti(sql, paramMap);
      }
      if ((infoList != null) && (infoList.size() > 0)) {
        Hashtable iMap = new Hashtable();
        for (int i = 0; i < infoList.size(); i++) {
          String tempStr = inStr;
          String tagName = "articleField";
          iMap = (Hashtable)infoList.get(i);
          String contentTagBody = "[content-value/]";
          String pageTagName = "[pagetags/]";

          while (this.tagUtil.CheckTag(this.cmsName, tagName, tempStr)) {
            String tagBody = this.tagUtil.getNoonLoopTagName(this.cmsName, tagName, tempStr);

            Hashtable paraMap = this.tagUtil.getTagPara(this.cmsName, tagName, tagBody);

            if ((paraMap == null) || (paraMap.size() < 1))
              break;
            String name = "";
            if (paraMap.get("name") != null) {
              name = paraMap.get("name").toString();
            }
            if (name.equals("content"))
              tempStr = tempStr.replace(tagBody, contentTagBody);
            String keyValue = "";
            if (iMap.get(name) != null) {
              keyValue = iMap.get(name).toString();
            }
            String sfValue = this.sField.getArticleVlaue(name, iMap);
            if (!sfValue.equals("")) {
              keyValue = sfValue;
            }
            tempStr = tempStr.replace(tagBody, keyValue);
          }

          this.articlelistTagEnable = true;
          tempStr = updateHtml(tempStr, iMap);

          String info_id = ""; String in_date = ""; String content = "";
          if (iMap.get("info_id") != null)
            info_id = iMap.get("info_id").toString();
          if (iMap.get("in_date") != null) {
            in_date = iMap.get("in_date").toString();
            if (in_date.length() > 10) {
              in_date = in_date.substring(0, 10);
            }
          }
          boolean isContentPage = true;
          if (iMap.get("content") != null) {
            content = iMap.get("content").toString();
          }

          if (this.conf.getString("conentpage").equals("0")) {
            String pageTag = "<div style=\"page-break-after: always\"><span style=\"display: none\">&nbsp;</span></div>";
            String patternStr = "(?is)<div style=\"page-break-after: always;\">(.*?)<span style=\"display: none;\">&nbsp;</span></div>";
            Pattern p = Pattern.compile(patternStr);
            Matcher m = p.matcher(content);
            content = m.replaceAll(pageTag);
            String pattern = pageTag;
            String[] strSplit = content.split(pattern);
            int count = strSplit.length;

            if (count > 1) {
              StringBuffer link_str = new StringBuffer();
              for (int b = 0; b < count; b++) {
                String info_xuhao = "";
                if (b != 0) info_xuhao = "-" + (b + 1);
                String link_path = save_dir + in_date + "/" + info_id + info_xuhao + ".html";
                link_str.append("<a href='/" + link_path + "'>" + (b + 1) + "</a>");
              }
              for (int k = 0; k < count; k++) {
                String textTempStr = tempStr;
                String thisText = "";
                thisText = strSplit[k];
                textTempStr = textTempStr.replace(contentTagBody, thisText);
                textTempStr = textTempStr.replace(pageTagName, link_str);

                String info_xuhao = "";
                if (k != 0) info_xuhao = "-" + (k + 1);
                String index_path = this.ecms_path + save_dir + in_date + "/";
                String html_file = index_path + info_id + info_xuhao + ".html";
                saveToFile(html_file, index_path, textTempStr);
              }
              isContentPage = false;
            }
          }
          if (isContentPage) {
            tempStr = tempStr.replace(contentTagBody, content);
            tempStr = tempStr.replace(pageTagName, "");
            String index_path = this.ecms_path + save_dir + in_date + "/";
            String html_file = index_path + info_id + ".html";
            saveToFile(html_file, index_path, tempStr);
          }
          jdbcDbm.ExecSql("delete from ti_createlog where info_id='" + info_id + "'");
        }
      }
      infoList = null;
      inStr = null;
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void updateWeb(String index_temp, String save_dir, String default_page, Hashtable paramMap)
  {
    String temp_file = this.ecms_path + index_temp;
    String inStr = this.fileUtil.getContentFromFile(temp_file);
    paramMap.put("ecms_path", this.ecms_path);
    inStr = updateHtml(inStr, paramMap);
    String html_file = this.ecms_path + "/" + save_dir + "/" + default_page;
    String index_path = this.ecms_path + "/" + save_dir + "/";
    saveToFile(html_file, index_path, inStr);
    inStr = null;
  }

  public String updateHtml(String inStr, Hashtable<String,String> paramMap)
  {
    try {
      ArrayList<Hashtable<String, String>> tagList = this.parseHtml.getinitList();
      if (inStr.equals("")) return "";
      if ((tagList != null) && (tagList.size() > 0)) {
        Hashtable<String, String> tagMap = new Hashtable<String, String>();
        for (int i = 0; i < tagList.size(); i++) {
          String tagName = ""; String tagType = ""; String tagValue = "";
          tagMap = (Hashtable<String, String>)tagList.get(i);
          if (tagMap.get("name") != null)
            tagName = tagMap.get("name").toString();
          if (tagMap.get("type") != null)
            tagType = tagMap.get("type").toString();
          if (tagMap.get("value") != null) {
            tagValue = tagMap.get("value").toString();
          }
          paramMap.put("tagValue", tagValue);

          if (!this.articlelistTagEnable) 
        	  do {
	              if (!this.tagUtil.CheckTag(this.cmsName, tagName, inStr)) break;
	              if (tagType.equals("article")) {
	                Hashtable infoMap = this.parseNoonLoop.getInfoMapBySql(paramMap);
	
	                inStr = this.parseNoonLoop.createArticle(this.cmsName, tagName, inStr, infoMap);
	              }
	
	              if (tagType.equals("include")) {
	                inStr = this.parseNoonLoop.includeFile(this.cmsName, tagName, inStr, paramMap);
	              }
	
	              if (tagType.equals("list")) {
	                inStr = this.parseLoop.createList(this.cmsName, tagName, inStr, paramMap);
	              }
	
	              if (tagName.equals("web_config")) {
	                inStr = inStr.replace("{zlcms:web_config webtitle/}", webtitle);
	                inStr = inStr.replace("{zlcms:web_config noimg_path/}", noimg_path);
	                inStr = inStr.replace("{zlcms:web_config weburl/}", weburl);
	                inStr = inStr.replace("{zlcms:web_config icp_filepath/}", icp_filepath);
	                inStr = inStr.replace("{zlcms:web_config icpno/}", icpno);
	                inStr = inStr.replace("{zlcms:web_config reg_send_mail/}", reg_send_mail);
	                inStr = inStr.replace("{zlcms:web_config is_reg/}", is_reg);
	                inStr = inStr.replace("{zlcms:web_config lose_reason/}", lose_reason);
	                inStr = inStr.replace("{zlcms:web_config logourl/}", logourl);
	                inStr = inStr.replace("{zlcms:web_config goodss_list_url/}", goodss_list_url);
	                inStr = inStr.replace("{zlcms:web_config goods_article_path/}", goods_article_path);
	                inStr = inStr.replace("{zlcms:web_config company_shop_path/}", company_shop_path);
	              }
            }
            while (!tagType.equals("articlelist"));
          else{
            while (this.tagUtil.CheckTag(this.cmsName, tagName, inStr)) {
              if (tagType.equals("article")) {
                Hashtable infoMap = this.parseNoonLoop.getInfoMapBySql(paramMap);

                inStr = this.parseNoonLoop.createArticle(this.cmsName, tagName, inStr, infoMap);
              }

              if (tagType.equals("include")) {
                inStr = this.parseNoonLoop.includeFile(this.cmsName, tagName, inStr, paramMap);
              }

              if (tagType.equals("list")) {
                inStr = this.parseLoop.createList(this.cmsName, tagName, inStr, paramMap);
              }

              if (tagType.equals("articlelist")) {
                inStr = this.parseLoop.createList(this.cmsName, tagName, inStr, paramMap);
              }

              if (tagName.equals("web_config")) {
                inStr = inStr.replace("{zlcms:web_config webtitle/}", webtitle);
                inStr = inStr.replace("{zlcms:web_config noimg_path/}", noimg_path);
                inStr = inStr.replace("{zlcms:web_config weburl/}", weburl);
                inStr = inStr.replace("{zlcms:web_config icp_filepath/}", icp_filepath);
                inStr = inStr.replace("{zlcms:web_config icpno/}", icpno);
                inStr = inStr.replace("{zlcms:web_config reg_send_mail/}", reg_send_mail);
                inStr = inStr.replace("{zlcms:web_config is_reg/}", is_reg);
                inStr = inStr.replace("{zlcms:web_config lose_reason/}", lose_reason);
                inStr = inStr.replace("{zlcms:web_config logourl/}", logourl);
                inStr = inStr.replace("{zlcms:web_config goodss_list_url/}", goodss_list_url);
                inStr = inStr.replace("{zlcms:web_config goods_article_path/}", goods_article_path);
                inStr = inStr.replace("{zlcms:web_config company_shop_path/}", company_shop_path);
              }
            }
          }
        }
      }

      tagList = null;
      return inStr; 
      } catch (Exception e) {
    	  e.printStackTrace();
    	  throw new RuntimeException();
    }
    
  }

  public void saveToFile(String html_file, String index_path, String tempStr)
  {
    try
    {
      this.fileUtil.makeDir(index_path);
      this.fileUtil.saveToFile(tempStr, html_file);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void updateWeb2(String index_temp, String save_dir, String default_page, Hashtable<String,String> paramMap)
  {
    String inStr = this.fileUtil.getContentFromFile(index_temp);//��ȡҳ��html�ļ�  "/WebRoot/templets/html/shop/index.html"
    paramMap.put("ecms_path", this.ecms_path);//this.ecms_path   ��·��
    inStr = updateHtml(inStr, paramMap);
    String html_file = this.ecms_path + "/" + save_dir + "/" + default_page;
    String index_path = this.ecms_path + "/" + save_dir + "/";
    saveToFile(html_file, index_path, inStr);
  }
  public static void main(String[] args) {
  }
  static {
    if (cfg == null) {
      cfg = new Config();
      cfg.init("config.properties");
    }

    noimg_path = cfg.getString("noimg_path");
    webtitle = cfg.getString("webtitle");
    weburl = cfg.getString("weburl");
    icp_filepath = cfg.getString("icp_filepath");
    icpno = cfg.getString("icpno");
    reg_send_mail = cfg.getString("reg_send_mail");
    is_reg = cfg.getString("is_reg");
    lose_reason = cfg.getString("lose_reason");
    logourl = cfg.getString("logourl");
    goodss_list_url = cfg.getString("goodss_list_url");
    goods_article_path = cfg.getString("goods_article_path");
    company_shop_path = cfg.getString("company_shop_path");
  }
}